//在线程调用函数中，传入运行函数的参数，传入pthread_create第四个参数

#include <iostream>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

void* say_hello(void* args) {
	cout << "hello in thread" << *((int*)args) << endl;
}

int main() {
	pthread_t tids[NUM_THREADS];
	int indexes[NUM_THREADS]; // 用数组来保存i的值，就不会变了
	for (int i = 0; i < NUM_THREADS; ++i) {
		indexes[i] = i; //先保存i的值，在调用线程时就不会出现问题了
		int ret = pthread_create(&tids[i], NULL, say_hello, (void*)&(indexes[i]));// 传入的时候必须为无类型指针 void*
		if (ret != 0) {
			cout << "pthread_create error: error_code=" << ret << endl;
		}
	}
	for (int i = 0; i < NUM_THREADS; ++i) {
		pthread_join(tids[i], NULL);
	}
}